import React, { useEffect, useState } from 'react';
import { Button, Radio, Select, Table, Input } from 'antd';
import { connect } from 'umi';
import { ConnectState } from '@/models/connect';

import { ViewModelTypes, ViewModelTypesLocale, ViewModelVisualTypesLocale } from './constants';

interface StructureTabelProps {
  modelDatasource: any;
  saveSheet: (data: string) => void;
  loading?: boolean;
  permissionList: Array<any>;
  sheetId: number
}

const StructureTabel: React.FC<StructureTabelProps> = (props) => {
  const { modelDatasource, saveSheet, loading, permissionList, sheetId } = props;
  const [editId, setEditId] = useState<any>(null); // 唯一标识
  const [edit, setEdit] = useState<boolean>(false); // 是否编辑中
  const [editModel, setEditModel] = useState<any>(null); // 编辑后的model
  const [dataSource, setDataSource] = useState<any[]>([]); // 编辑后的model

  // 更改数据表
  const modelChange = (value: string, record: any, type: string) => {

    const data = editModel || JSON.parse(modelDatasource);
    data[record.name][type] = value;
    if (value === '' && type === 'dataRoleType') {
      delete data[record.name][type];
    }
    //指标的要去掉数据行权限
    if (value === ViewModelTypes.Value && type === 'modelType') {
      delete data[record.name].dataRoleType;
    }
    setEditId(sheetId);
    setEditModel(data);
  };

  const save = () => {
    setEdit(false);
    saveSheet(editModel);
    setEditId(null);
    setEditModel(null);
  };


  const columns = [
    {
      title: '字段名称',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: '别名',
      dataIndex: 'alias',
      editable: true,
      render: (text: string, record: any) => {
        return (
          <Input
            disabled={!edit}
            defaultValue={text}
            onChange={(e) => {
              modelChange(e.target.value, record, 'alias');
            }}
          />
        );
      },
    },
    {
      title: '数据类型',
      dataIndex: 'modelType',
      render: (text: string, record: any) => (
        <Radio.Group
          disabled={!edit}
          onChange={(e) => {
            modelChange(e.target.value, record, 'modelType');
          }}
          defaultValue={text}
        >
          {Object.entries(ViewModelTypesLocale).map(([value, label]) => (
            <Radio value={value} key={value}>
              {label}
            </Radio>
          ))}
        </Radio.Group>
      ),
    },
    {
      title: '可视化类型',
      dataIndex: 'visualType',
      render: (text: string, record: any) => (
        <Select
          style={{ width: 140 }}
          defaultValue={text}
          disabled={!edit}
          onChange={(value) => {
            modelChange(value, record, 'visualType');
          }}
        >
          {Object.entries(ViewModelVisualTypesLocale).map(([visualType, text]) => (
            <Select.Option key={visualType} value={visualType}>
              {text}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '行权限',
      dataIndex: 'dataRoleType',
      render: (text: string, record: any) => {
        if (editModel && editId === sheetId) {
          if (editModel[record.name].modelType !== ViewModelTypes.Category) {
            return;
          }
          text = editModel[record.name].dataRoleType ? editModel[record.name].dataRoleType : '';
        } else {
          if (record.modelType !== ViewModelTypes.Category) {
            return;
          }
        }
        return (
          <Select
            style={{ width: 140 }}
            defaultValue={text}
            disabled={!edit}
            onChange={(value) => {
              modelChange(value, record, 'dataRoleType');
            }}
          >
            <Select.Option value='' key={0}>
              无
            </Select.Option>
            {permissionList.map((v: any) => {
              if (v.isEnable) {
                return (
                  <Select.Option value={v.no} key={v.no}>
                    {v.name}
                  </Select.Option>
                );
              }
              return '';
            })}
          </Select>
        );
      },
    },
  ];
  useEffect(() => {
    setEdit(false);
    setEditModel(null);
  }, [props.sheetId]);
  useEffect(() => {
    if (modelDatasource) {
      const dataSource: any[] = [];
      const model = JSON.parse(modelDatasource);
      Object.keys(model).forEach((key => {
        let obj = {
          name: key,
          alias: model[key].alias,
          modelType: model[key].modelType,
          visualType: model[key].visualType,
          dataRoleType: model[key].dataRoleType || '',
          key: `${key}-${sheetId}`,
        };
        dataSource.push(obj);
      }));

      setDataSource(dataSource);
    }
  }, [props.modelDatasource]);
  return (
    <div>
      <div style={{ marginBottom: '20px', textAlign: 'right' }}>
        <Button
          style={{ marginRight: '20px' }}
          disabled={edit}
          onClick={() => {
            setEdit(true);
          }}
        >
          编辑
        </Button>
        <Button type='primary' disabled={!edit} onClick={save}>
          保存
        </Button>
      </div>
      <Table
        bordered
        pagination={false}
        columns={columns}
        dataSource={dataSource}
        loading={loading}
      />
    </div>
  );
};

export default connect(({ loading }: ConnectState) => ({
  loading: loading.effects['sheet/fetchSheetList'],
}))(StructureTabel);
